﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using Infragistics.Win.UltraWinGrid;
namespace DMSClient
{
    public partial class Visit : Form
    {
        
        private DataTable dtVisit;
        string ambiente;
        EndpointAddress address;
        WSHttpBinding Binding = new WSHttpBinding();
        public Visit()
        {           
           
            InitializeComponent();           
            ambiente = Properties.Settings.Default.CurrentEnv;
            Binding.MaxReceivedMessageSize = 2147483647;
            Binding.MaxBufferPoolSize = 2147483647;
            Binding.ReceiveTimeout = TimeSpan.MaxValue;
            Binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
            Binding.Security.Mode = SecurityMode.None;
            address = new EndpointAddress(Properties.Settings.Default.Server);

            this.Text = Properties.Settings.Default.CurrentEnvDes + " - Visit Report";

            uceDistributors.DisplayMember = "cdOrgUnit";
            uceDistributors.ValueMember = "idOrgUnit";
            string distributors = null;

            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);

            try
            {
                client.Open();
                distributors = client.getDistributorsList(ambiente);
                client.Close();
            }
            catch (Exception ex)
            {
                throw new Exception(Properties.Settings.Default.DistributorsListErrorMsg, ex.InnerException);
            }
            if (distributors == null)
            {
                throw new Exception(Properties.Settings.Default.DistributorsNullListErrorMsg);
            }

            DataTable dt = new DataTable("dtDistributorsList");
            dt.Columns.Add("idOrgUnit");
            dt.Columns.Add("cdOrgUnit");


            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            System.IO.StringReader xmlSR = new System.IO.StringReader(distributors);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            uceDistributors.DataSource = ds.Tables[0];
            uceDistributors.SelectedIndex = 0;

            xmlSR.Close();

            /*   ugGridVisit.DisplayLayout.Bands[0].Columns.Add("cdVisit", "cdVisit");
               ugGridVisit.DisplayLayout.Bands[0].Columns.Add("cdRegion", "cdRegion");
               ugGridVisit.DisplayLayout.Bands[0].Columns.Add("cdStore", "cdStore");
               ugGridVisit.DisplayLayout.Bands[0].Columns.Add("cdUser", "cdUser");
               ugGridVisit.DisplayLayout.Bands[0].Columns.Add("dtStart", "dtStart");
               ugGridVisit.DisplayLayout.Bands[0].Columns.Add("cdStatus", "cdStatus");*/
            udStartDate.Value = udEndDate.Value = DateTime.Now;
            
        }

        private void ultraButton1_Click(object sender, EventArgs e)
        {
            WorkerVisit.RunWorkerAsync();
            estado(false);
            
           
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            
        }

        private void WorkerVisit_DoWork(object sender, DoWorkEventArgs e)
        {

            BackgroundWorker worker = sender as BackgroundWorker;

            DMSServices.DMSServicesClient client;
            client = new DMSServices.DMSServicesClient(Binding, address);
            string lista = null;
            try
            {
                client.Open();
                lista = client.getVisitReport(uceDistributors.Value.ToString(), DateTime.Parse(udStartDate.Value.ToString()), DateTime.Parse(udEndDate.Value.ToString()), ambiente);
                client.Close();

                if (worker.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex.InnerException);
            }
            if (lista == null)
            {
                throw new Exception("Error");
            }
    
            dtVisit = new DataTable("Visitdt");
            dtVisit.Columns.Add("idOrgUnit");
            dtVisit.Columns.Add("cdVisit");
            dtVisit.Columns.Add("cdRegion");
            dtVisit.Columns.Add("dsRegion");
            dtVisit.Columns.Add("cdStore");
            dtVisit.Columns.Add("cdUser");
            dtVisit.Columns.Add("dtOriginalPlannedStart");
            dtVisit.Columns.Add("dtStart");
            dtVisit.Columns.Add("cdStatus");
            dtVisit.Columns.Add("dtPlannedEnd");
           // dtVisit.Columns.Add("dtLastModify"); 
           
            DataSet ds = new DataSet();
            ds.Tables.Add(dtVisit);

            System.IO.StringReader xmlSR = new System.IO.StringReader(lista);
            ds.ReadXml(xmlSR, XmlReadMode.ReadSchema);
            
            xmlSR.Close();
        }

        private void WorkerVisit_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                if (!this.IsDisposed)
                {
                    this.BringToFront();
                    MessageBox.Show(this, e.Error.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    estado(true);
                }
            }
            else if (!e.Cancelled && !this.IsDisposed)
            {
                ugGridVisit.DataSource = dtVisit;
                loader.Visible = false;
                estado(true);
            }
        }

        public void estado(bool estado)
        {
            uceDistributors.Enabled = estado;
            Consultar.Enabled = estado;
           // Tab.Controls[2].Enabled = estado;
            loader.Visible = !estado;
            udStartDate.Enabled = estado;
            udEndDate.Enabled = estado;
            Export.Enabled = estado;
            
        }

        private void ultraButton1_Click_1(object sender, EventArgs e)
        {
            if (ugGridVisit.Rows.Count < 1)
            {
                MessageBox.Show(this, "There is no data to export", "Visit Report", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            System.Windows.Forms.SaveFileDialog dialogo = new System.Windows.Forms.SaveFileDialog();
            dialogo.DefaultExt = "xls";
            Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter Exporter = new Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter();
            
            if (dialogo.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Exporter.Export(ugGridVisit, dialogo.FileName);
                if (MessageBox.Show(this, "¿Desea abrir el archivo?", "Visit Report", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(dialogo.FileName);
                }
            }
        }

        private void Visit_Shown(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void Visit_Resize(object sender, EventArgs e)
        {
            loader.Left = (this.Width - loader.Width) / 2;
            loader.Top = ((this.Height - loader.Height) / 2) - loader.Height;
        }

        private void ugGridVisit_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {

        }

        private void ultraGroupBox1_Click(object sender, EventArgs e)
        {

        }

        private void ugGridVisit_InitializeLayout_1(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            foreach (UltraGridColumn ugc in e.Layout.Bands[0].Columns)
            {
                ugc.PerformAutoResize(PerformAutoSizeType.AllRowsInBand, true);
            }
        }

        private void Visit_FormClosing(object sender, FormClosingEventArgs e)
        {

            if (WorkerVisit.IsBusy)
            {
                WorkerVisit.CancelAsync();
            }
        }

        private void Visit_Load(object sender, EventArgs e)
        {

        }

        
    }
}
